package cn.edu.guet.bll.editor.impl;

import cn.edu.guet.bean.editor.EditorUser;
import cn.edu.guet.bean.editor.Post;
import cn.edu.guet.bll.editor.PostBll;
import cn.edu.guet.mapper.editor.PostMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * create by hzg 2021/07/07
 * 帖子的各个业务实现类
 */
@Service
public class PostBllImpl implements PostBll {
    @Autowired
    private Post postBean;
//    public void setPostBean(Post postBean){ this.postBean = postBean; }

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    @Override
    public void publishPost(String type, String title, String content,String time,String pstatus) {
        postBean.setPtitle(title);
        postBean.setPtime(time);
        postBean.setPtype(type);
        postBean.setPcontent(content);
        postBean.setPstatus(pstatus);
        postBean.setUserid("1");//获取Session中的用户对象
        //获取Spring中的sqlsession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //生成一个代理对象
        PostMapper postMapper=sqlSession.getMapper(PostMapper.class);
        postMapper.insertPost(postBean);
        //mybatis并非自动提交事务
        sqlSession.commit();
    }

    @Override
    public Post selectPostById(String pid) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PostMapper postMapper = sqlSession.getMapper(PostMapper.class);
        postBean = postMapper.selectPostById(pid);
        return postBean;
    }

    @Override
    public EditorUser selectUserById() {
        //暂时获取不了所以先写1
        String userid = "1";
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PostMapper postMapper = sqlSession.getMapper(PostMapper.class);
        EditorUser editorUser = postMapper.selectUserById(userid);
        return editorUser;
    }

    @Override
    public void giveupPost(String pid,String userid) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PostMapper postMapper = sqlSession.getMapper(PostMapper.class);
        //在点赞表中加入记录
        postMapper.insertGiveup(pid,userid);
        //先查询当前点赞数量,在点赞数量的基础上加一
        int con = postMapper.selectPostGiveup(pid)+1;
        //更新点赞数量
        postMapper.updatePostGiveup(con,pid);
        sqlSession.commit();
    }

    @Override
    public void collectPost(String userid, String pid) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PostMapper postMapper = sqlSession.getMapper(PostMapper.class);
        postMapper.collectPost(userid,pid);
        sqlSession.commit();
    }

    @Override
    public void deletePost(String pid) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        PostMapper postMapper = sqlSession.getMapper(PostMapper.class);
        postMapper.deletePost(pid);
        sqlSession.commit();
    }
}
